import TickerMgr from "./TickerMgr";

export default class TimeTicker{
  public delay: number = 0;
  public repeatCount: number = 0;
  public tickTime: number = 0;
  public tickCount: number = 0;
  public timerFunc: Function;
  public compFunc: Function;
  public updateParams: any;
  public completeParams: any;
  constructor(
    delay_: number,
    repeatCount_: number = 0,
    timerFunc_: Function = null,
    compFunc_: Function = null
  ) {
    this.timerFunc = timerFunc_;
    this.compFunc = compFunc_;
    this.delay = Math.abs(delay_);
    this.repeatCount = Math.max(0, repeatCount_);
    this.reset();
  }

  public start(): void {
    TickerMgr.instance.addTicker(this);
  }
  public stop(): void {
    TickerMgr.instance.removeTicker(this);
  }

  public reset(): void {
    this.tickCount = 0;
    this.tickTime = 0;
  }
  public doTick(dtime: number): void {
    this.tickTime += dtime;
    if (this.tickTime >= this.delay) {
      this.tickTime = 0;
      ++this.tickCount;
      if (this.timerFunc != null) {
        this.timerFunc.apply(null, this.updateParams);
      }
      if (this.repeatCount > 0 && this.tickCount >= this.repeatCount) {
        if (this.compFunc != null) {
          this.compFunc.apply(null, this.completeParams);
        }
        this.dispose();
        return;
      }
    }
  }

  public dispose(): void {
    this.stop();
    this.reset();
    this.timerFunc = null;
    this.compFunc = null;
    this.updateParams = null;
    this.completeParams = null;
  }
}
